###########################################################################
# Lipps & Voeten
# Voting with Putin:
# Gender, LGBT Rights, and Tacit Support for Russia among Europe's Parliamentarians
# Comparative Political Studies

# Main replication file --------------------------------------------------
###########################################################################

rm(list = ls())

packages <- c("fixest", "tidyverse", "corrplot", "psych", "broom", "ggplot2", "ggpubr")

for (package in packages) {
  if (!requireNamespace(package, quietly = TRUE)) {
    install.packages(package, dependencies = TRUE)
  }
}

#Packages
library(fixest)
library(tidyverse)
library(corrplot)
library(psych)
library(broom)
library(ggplot2)
library(ggpubr)

#setwd("C:/Users/lippsj/Dropbox/PACE/Replication")

#load data
votesrussia <- readRDS("PACE_Russia_votes.rds")
declarations <- readRDS("PACE_LGBT_declarations.rds")

#Labels of main variables
dict = c(v2pagender = "Women party leadership", government = "Opposition", Equality="Cultural Liberalism",
         female="Female", v2pawomlab = "Women in labor force", v2palgbt = "LGBT rights",
         Y = "Pro-Russia vote", v2paculsup = "Cultural superiority", v2xpa_popul ="Populism",
         v2pariglef = "Economic left-right", v2xpa_illiberal = "Party illiberalism",
         voteid = "Vote ID", natparty_vpartyname = "National Party", signator="Signed LGBT declaration",
         dove="Dovishness", country="Country", party_clean="Party group", year="Year", rile="Left-Right (pm)", 
         eu_position = "European integration (CHES)", lrgen = "Left-Right (CHES)",   lrecon = "Left-Right, econ (CHES)",
         galtan = "Galtan, (CHES)", civlib_laworder = "civil liberties {CHES)",   sociallifestyle = "social lifestyle",
         us = "US power (CHES)", russian_interference = "Russian interference (CHES)", postpussy = "Post Pussy Riot Performance",
         signat.all = "Signed LGBT Declaration", signat.notrussia = "Signed LGBT Declaration, not Russia")

#Post conservative turn
cutoff_date <- as.Date("2012-02-21")
votesrussia$postpussy <- ifelse(votesrussia$docdate >= cutoff_date, 1, 0)


#Replication code----------------------------------------------------------

#Figure 1: The number of LGBT declarations (bar) and the number of signatories (line) over time
declsum <- declarations %>%
  group_by(year, targetrussia) %>%
  summarize(
    sum_count = sum(nosig, na.rm = TRUE),
    unique_docs = n_distinct(docno),
    .groups = "drop")

declsum <- declsum %>%
  complete(year = full_seq(declsum$year, 1), targetrussia = c(0, 1), fill = list(sum_count = 0, unique_docs = 0))

declsum$targetrussia <- as.factor(declsum$targetrussia)

pdf(file="main_fig1.pdf", width=10, height=7)
ggplot(declsum) +
  geom_line(aes(x=year, y=sum_count, color=targetrussia), linewidth=1.2) +
  geom_col(aes(x=year, y=unique_docs*100, fill=targetrussia), alpha=0.4) +
  scale_color_manual(values=c("black", "darkred"), name="", labels=c("All Declarations", "Targeting Russia")) +
  scale_fill_manual(values=c("black", "darkred")) +
  guides(fill="none") +
  scale_y_continuous(name = "No. of MPs that signed (line)",
                     sec.axis = sec_axis(transform=~./100, name="No. of Declarations circulating (bar)")) +
  labs(x="") +
  scale_x_continuous(breaks=c(2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023))+
  theme_bw() +
  theme(
    axis.text = element_text(size = 14),
    axis.title = element_text(size = 16),
    panel.grid = element_blank(),
    legend.position = "top",
    legend.text = element_text(size = 16))
dev.off()

#Figure 2: Average Support for Russian Position by country delegation

#coding threat perception according to Meijer and Brook (2021)
bycountry <- votesrussia %>% 
  mutate(color= as.factor(case_when(country %in% c("RU", "RS", "AM", "AZ", "BA") ~ 1,
                                  country %in% c("BG", "GR", "HU", "IE", "IT", "LU", "ES", "SI", "PT", "AT", "CH", "LI", "FR", "HR", "DE", "UK", "NL", "BE", "DK", "CY", "AD", "SM", "MT", "MC", "TR", "ME", "IS")~ 2, 
                                  country %in% c("CZ", "NO", "RO", "SK", "SE", "FI", "EE", "LT", "LV", "PL", "UA", "GE", "MD", "AL", "MK") ~ 3))) %>%
  group_by(country) %>% 
  summarize (Russiasupport=mean(as.numeric(Y), na.rm = TRUE), color=first(color))

pdf(file="main_fig2.pdf", width=8, height=9)
ggplot(bycountry, aes(y=Russiasupport, x=reorder(country, Russiasupport), fill=color)) + 
  geom_bar(position=position_dodge(0.7), stat="identity") + 
  scale_fill_manual(values=c("black", "darkgrey", "darkred"), name="", labels=c("Russia high threat", "Russia not high threat", "Russian ally")) +
  coord_flip() + xlab("") +
  ylab("Average Support for Russian positions") + theme_light() +
  theme(legend.position = "top",
        legend.text = element_text(size=16),
        axis.title = element_text(size=16),
        axis.text = element_text(size=16))
dev.off()

#Figure 3: Average Support for Russian Position by PACE party group over time
votesrussia %>% group_by(party_clean, year) %>%
  summarize(Y = mean(Y)) ->partygroup

pdf(file="main_fig3.pdf", width=9.5, height=6)
ggplot(partygroup, aes(x=year, y=Y, color=party_clean)) +
  geom_line(linewidth=1.25) +
  scale_color_manual(values = c("orange", "blue", "darkblue", "black", "grey", "red", "darkred"), name="PACE group")+
  scale_x_continuous(breaks=c(2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022))+
  labs(x="", y="Average support for Russian positions") +
  theme_bw() +
  theme(legend.position = "top",
        legend.text = element_text(size=16),
        axis.title = element_text(size=16),
        axis.text = element_text(size=16))
dev.off()

#Table 1: Regression on all votes, all countries

# Testing the effect of individual gender and ideology in a party fixed effects model
model1 <- as.formula("Y ~   female + Equality + v2pagender | voteid + natparty_vpartyname")
model2 <- as.formula("Y ~   signat.all + Equality + v2pagender  | voteid + natparty_vpartyname")
model3 <- as.formula("Y ~   i(female, signat.all, ref=0) + female + signat.all + Equality + v2pagender | voteid + natparty_vpartyname")

#Testing whether the effect of party level variables is robust across country-year
#and estimating the interaction between party ideology and individual gender/ideology
model4 <- as.formula("Y ~   Equality + v2pagender | voteid + country^year")
model5 <- as.formula("Y ~   i(female, Equality, ref=0) + female + Equality + v2pagender | voteid + country^year")
model6 <- as.formula("Y ~   i(signat.all, Equality, ref=0) + signat.all + Equality + v2pagender | voteid + country^year")

#All votes, all parties, all countries
M1 = feols(model1, votesrussia)
M2 = feols(model2, votesrussia)
M3 = feols(model3, votesrussia)
M4 = feols(model4, votesrussia)
M5 = feols(model5, votesrussia)
M6 = feols(model6, votesrussia)

etable(list(M1, M2, M3, M4, M5, M6), digits = "r3", dict=dict,
       order = c("^Female", "^Signed LGBT Declaration", "Women leadership", "Cultural Liberalism"),
       file = "TableAll_revision.tex", replace = TRUE, 
       title = "Regression on All Votes, all countries")

#Figure 4: The interaction effect of gender and pro-LGBT support by type of vote
votes_domest <- votesrussia %>% filter(international_handc==0)
votes_internat <- votesrussia %>% filter(international_handc==1 & russiamem==0)
M3domes = feols(model3, votes_domest)
M3inter = feols(model3, votes_internat)

results <- tidy(M3) %>% mutate(model= "all")
resultsintd <- tidy(M3domes) %>% mutate(model="domes")
resultsinti <- tidy(M3inter) %>% mutate(model="international")
comdint <- rbind(results, resultsinti, resultsintd) %>% filter(str_detect(term, "signat.all") | str_detect(term, "female"))
comdint$model <- ordered(comdint$model, levels=c("all", "international", "domes"))

pdf(file="main_fig4.pdf",width = 9,height = 7)
ggplot(comdint, aes(x = term, y = estimate, ymin=estimate-(1.96*std.error), ymax=estimate+(1.96*std.error), shape=model, color=model)) +
  geom_errorbar(width=0.3, size=1, position="dodge") +
  geom_point(position = position_dodge2(width=0.3, preserve = "total"), stat="identity", size=4) +
  geom_hline(yintercept=0) +
  scale_x_discrete(labels = c("Female", "Female * Signatory", "Signatory")) +
  scale_color_grey(name="Type of votes", labels= c("All votes", "International Votes", "Domestic Votes")) +
  scale_shape_discrete(name="Type of votes", labels= c("All votes", "International Votes", "Domestic Votes")) +
  labs(x = "", y = "Estimate and 95% Conf. Int.", title = "") +
  theme_bw() +
  theme(
    axis.text.x = element_text(size = 16),
    axis.text.y = element_text(size = 16),
    axis.title = element_text(size = 16),
    legend.position = "inside",
    legend.position.inside = c(0.851,0.9),
    legend.text = element_text(size = 16),
    legend.title = element_text(size = 16),
    legend.background = element_rect(size=0.5, linetype="solid",color ="black"),
    panel.grid.major = element_line(colour = 'grey', linetype = 'dashed'),
    title = element_text(size = 12, vjust = 0.5))
dev.off()

#Figure 5: The effect of gender before and after Putin's cultural conservative turn

modelpussy <- as.formula("Y ~  female*postpussy | voteid + natparty_vpartyname")
M1pussy = feols(modelpussy, votesrussia)
M2pussy = feols(modelpussy, votes_domest)
M3pussy = feols(modelpussy, votes_internat)

pdf(file = "main_fig5.pdf",width = 8,height = 5,onefile=F)
coefplot(list(M1pussy, M2pussy, M3pussy),
         ci.col=c("black", "grey48", "grey80"), pt.col= c("black", "grey48", "grey80"), ci.width=0.04, cex= 2, lwd=2.75,text.cex=16,
         dict=c(female="Female", "female:postpussy"="Female x Post-Pussy Riot"), main="")
legend("topright", col = c("black", "grey48", "grey80"), pch = c(16,17,15), lwd = 1.25, legend = c("All Votes", "International Votes","Domestic Votes"), title = "Type of Votes")
dev.off()

#Figure 6: for matching results, see separate script "replication_matching.R"

#Figure 7: Interaction of party ideology with gender and with individual LGBT rights support

#Break into quantiles
votesrussia$Qequal <- cut(votesrussia$Equality, breaks = quantile(votesrussia$Equality, probs = seq(0, 1, 0.333), na.rm = T),
                 include.lowest = T, right = F, labels =  c("Conservative", "Medium", "Liberal"))

modelint1 <- as.formula("Y ~   i(female, Qequal, ref=0) + female + Qequal + v2pagender | voteid + country^year")
modelint2 <- as.formula("Y ~   i(signat.all, Qequal, ref=0) + signat.all + Qequal + v2pagender | voteid + country^year")
M1int = feols(modelint1, votesrussia)
M2int = feols(modelint2, votesrussia)

results1 <- tidy(M1int) %>% 
  filter(str_detect(term, "female")) %>% 
  mutate(variable = "Female")
results2 <- tidy(M2int) %>% 
  filter(str_detect(term, "signat.all")) %>% 
  mutate(variable = "Signatory")
combined_results <- bind_rows(results1, results2) %>% 
  mutate(liberalism_level = case_when(
    str_detect(term, "Qequal::Conservative") ~ "Conservative",
    str_detect(term, "Qequal::Medium") ~ "Moderate",
    str_detect(term, "Qequal::Liberal") ~ "Liberal")) %>%
  mutate(liberalism_level = factor(liberalism_level, levels = c("Conservative", "Moderate", "Liberal")))

pdf(file = "main_fig7.pdf",width = 8,height = 5.5,onefile=F)
ggplot(combined_results, aes(x = liberalism_level, y = estimate, color = variable, shape= variable, ymin=estimate-(1.96*std.error), ymax=estimate+(1.96*std.error))) +
  geom_errorbar(size=1, width=0.2, position="dodge") +
  geom_point(position = position_dodge2(width=0.2, preserve = "total"), stat="identity", size=4) +
  geom_hline(yintercept=0, color="black") +
  scale_color_grey(name="MP is...", labels= c("Female", "Signatory")) +
  scale_shape_discrete(name="MP is...", labels= c("Female", "Signatory")) +
  labs(x = "Party Cultural Liberalism", y = "Coefficient Estimate") +
  theme_bw() +
  theme(axis.text.x = element_text(size=16), 
        axis.text.y=element_text(size=16),
        axis.title = element_text(size= 16),
        legend.position = "inside",
        legend.position.inside = c(0.899,0.899),
        legend.text = element_text(size = 16),
        legend.title = element_text(size = 16),
        legend.background = element_rect(size=0.5, linetype="solid",color ="black"),
        panel.grid = element_line(colour = 'grey', linetype = 'dashed'))
dev.off()
